<template>
	<view>
		<uni-popup ref="selcon" zindex type="bottom" @maskClick="maskClick" :safeArea="false">
			<view class="comBotBx p_rlt" @touchmove.stop.prevent="" :class="{ipx:props.isPhonex}">
				<view class="text-xll text-bold padding-left padding-top">免费领优惠券</view>
				<!-- <view class="text-xl text-bold padding-left padding-top">优惠券</view> -->
				<scroll-view scroll-y scroll-with-animation class="sleScr">
					<view class="padding-lr-sm" style="position: relative;width: 100%;height:500rpx">
						<empty positions="absolute" :empty="checkCouplength<=0" :imgUrl="'https://cdn-static.yekjx.com/'+'food/empty/images/empty_ico04.png'" content="暂无优惠券" :zIndexs="100"></empty>
						<view class="cu-bar-yhj" v-for="(item,index) in coupList" :key="index">
							<view class="cubar_left">
								<view class="cu-bar-yhj-PicStyle">
									{{ item.content }}
									<text class="cu-bar-yhj-PicZk">{{item.coupon_type_two=='970'?'折':'元'}}</text>
								</view>
							</view>
							<view class="cubar_right">
								<view class="cu-bar-yhj-title padding-right-sm">{{ item.vname }}</view>
								<view class="flex justify-between align-center">
									<text class="cu-bar-yhj-left-time">有效期至{{ item.validity }}</text>
									<view class="cu-bar-yhj-right">
										<text v-if="item.status == '96'" class="cu-bar-yhj-rightBtn" style="background-color:#F3F3F3;color:#888888">已领完</text>
										<text v-else class="cu-bar-yhj-rightBtn"
											:style="{ backgroundColor: item.hasGet&& item.allUse && !item.canGet?'#666':'rgba(255, 104, 104, 0.10)',color:item.hasGet&& item.allUse && !item.canGet?'#666':'#EF0606'}"
											@click="getCouponItem(index, item)">
											{{!isLogin?'领取':(item.hasGet&&!item.allUse ? '立即使用' : (item.hasGet && item.allUse && item.canGet || !item.hasGet) ? '领取' :'已领取' )}}
										</text>
									</view>
								</view>
								<view class="cu-bar-yhj-left-rule point" @click="showMore(item)">
									规则说明<text class="lg text-gray margin-left-xs inblcok"
										:class="item.show?'cuIcon-fold':'cuIcon-unfold'"></text>
								</view>
								<view class="rule-con-ul padding-right-sm">
									<view class="rule-con" :class="{activeWy : item.show}">
										{{item.vdesc}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<view v-if="pomList.length>0">
					<view class="text-xl text-bold padding-left padding-top">优惠<text class="title_tips">（以下单为准）</text></view>
					<scroll-view scroll-y scroll-with-animation class="sleScrs">
						<view class="shopyh" v-for="(item,index) in pomList" :key="index">
							<view> <text class="fcon-zhekou"
									style="color: #FF7744;font-size:38rpx;margin-right:10rpx"></text>{{item.content}}</view>
						</view>
          </scroll-view>
				</view>
			</view>
		</uni-popup>
		<loading></loading>
	</view>
</template>

<script setup lang="ts">
	import { ref, defineEmits } from 'vue';
	import global from '@/utils/global';
	import { queryMenuPromotion, queryMenuPromotionList, memberGet, memberGetStatu } from '@/api/vmeitime-http/index.js'
	import { showLoading, hideLoading } from '@/utils/helper';
	import { onShow } from '@dcloudio/uni-app';
	import mapi from '@/utils/mapi';
	import { env } from '@/api/env.js'
	import { useShopStore } from '@/stores/shopStore';
	const props = defineProps({
		isPhonex:{
			type:Boolean,
			default:false
		}
	});
	const emit = defineEmits(["maskClick", "hasGet"])
	const shopStore = useShopStore();
	const selcon = ref()
	const coupList = ref([])
	const confirmNums = ref(0)
	const pomList = ref([])
	const isLogin=ref(false)
	const checkCouplength=ref(0)
	const pageSource=ref('')
	const loaded=ref(false)
	const open =(v:any) => {
		pageSource.value=v
		getSalesPromotion()
		if(v){
			selcon.value.open()
		}
	}
	onShow(()=>{
		isLogin.value = uni.getStorageSync(global.IS_LOGIN)||false
		!loaded.value&&getSalesPromotion()
	})
	const getSalesPromotion = async () => {
		loaded.value=true
		let cashCouponFinal = await queryMenuPromotionList({ pageSize: 20, curPage: 1, sellerMemberIds: shopStore.curSellerMemberId })
		coupList.value = []
		if (!cashCouponFinal.result) {
			return
		}
		let cashFinalResult = cashCouponFinal.object || []
		checkCouplength.value=cashFinalResult.length
		if(checkCouplength.value>0&&pageSource.value!=''){
			selcon.value.open()
		}
		for (let its of cashFinalResult) {
			coupList.value.push({
				...its,
				content: its.coupon_type_two == '970' ? parseRate(its.par_value) : its.par_value,
				allowReceive: true,
				show: false,
				validity: its.vactivity_end_time ? `${its.vactivity_end_time.slice(0, 4)}.${its.vactivity_end_time.slice(4, 6)}.${its.vactivity_end_time.slice(6, 8)}` : ''
			})
		}
		 getPomList()
	}
	const getPomList = async () => {
		let cashCoupon = await queryMenuPromotion({ sellerMemberd: shopStore.curSellerMemberId })
		pomList.value = []
		if (!cashCoupon.result) {
			return
		}
		let cashCouponResult = cashCoupon.object || []
		for (let i in cashCouponResult) {
			pomList.value.push({
				content: cashCouponResult[i],
			})
		}
	}
	const parseRate = (value : any) => {
		if (!isNaN(value)) {
			let num = value * 100;
			num = num % 10 === 0 ? num / 10 : num
			return num
		} else {
			return 0
		}
	}

	const close = () => {
		selcon.value.close()
	}
	const showMore = (item : any) => {
		item.show = !item.show;
	}
	const maskClick = (e : any) => {
		// console.log('car-maskClick',e);
		emit("maskClick")
	}
	const getCouponItem = async (index : any, item : any) => {
		if ((!(item.hasGet && item.allUse && item.canGet || !item.hasGet))&&isLogin.value) {
			close()
			return
		}
		try {
			showLoading()
			let res = await memberGet({ coupon_id: item.coupon_id })
			if (res.result === true || res.result === 'true') {
				let sessionId = res.object;
				checkCouponStatus(sessionId, index);
			} else {
				mapi.msg(res.shortMessage);
			}
		} catch (e) {
			hideLoading()
			mapi.msg('服务器繁忙，请稍后');
		}

	}
	const checkCouponStatus = async (sessionId : any, index : any) => {
		try {
			let res = await memberGetStatu({ sessionid: sessionId })
			if (res.state) {
				if (res.state === 'success') {
					hideLoading()
					coupList.value[index].hasGet = true
					coupList.value[index].allUse = false
					mapi.msg('领取成功！');
					console.log(coupList.value,"coupList.value")
					confirmNums.value = 0;
					emit('hasGet')
				} else if (res.state == 'fail' || (res.state == 'create' && res.messages != '')) {
					hideLoading()
					mapi.msg(res.messages || '服务器繁忙，请稍后尝试');
					confirmNums.value = 0;
				} else {
					confirmNums.value++;
					if (confirmNums.value < 5) {
						setTimeout(function () {
							checkCouponStatus(sessionId, index);
						}, 1000);
					} else {
						hideLoading()
						confirmNums.value = 0;
						mapi.msg('服务器繁忙，请稍后尝试');
					}
				}
			} else {
				hideLoading()
				mapi.msg(res.messages || '服务器繁忙，请稍后尝试');
				confirmNums.value = 0;
			}
		} catch (e) {
			hideLoading()
			mapi.msg('服务器繁忙，请稍后尝试');
		}

	}
	defineExpose({ open, close })
</script>

<style lang="scss" scoped>
	.comBotBx {
		padding-bottom: 32rpx;//30
		&.ipx{
			padding-bottom: 32rpx;
		}
		.sleScrs {
			min-height: 100rpx;
			max-height: 330rpx;
		}

		.sleScr {
			min-height: 300rpx;
			max-height: 500rpx;
			padding: 20rpx 0 0 20rpx;

			.cu-bar-yhj {
				display: flex;
				justify-content: space-between;
				width: 674rpx;
				min-height: 216rpx;
				border-radius: 8rpx;
				background: #FFF;
				box-shadow: 0px 0px 10px 0px rgba(212, 219, 238, 0.80);
				margin-top: 20rpx;
				margin-bottom: 20rpx;
			}

			.cubar_left {
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				width: 202rpx;
				border-radius: 4px 0px 0px 4px;
				position: relative;
				background-color: #FFF0F0;
				z-index: 12;

				&::before {
					content: '';
					width: 20rpx;
					height: 100%;
					position: absolute;
					right: -7rpx;
					top: 0;
					background-size: 25rpx 25rpx;
					background-image: radial-gradient(#fff 8rpx, transparent 6rpx);
					background-repeat: repeat-y;
				}

				.cu-bar-yhj-PicStyle {
					color: #F00;
					font-size: 60rpx;
					font-weight: 700;

					.cu-bar-yhj-PicZk {
						font-weight: 400;
						font-size: 24rpx;
					}
				}
			}

			.cubar_right {
				width: calc(100vw - 202rpx);
				min-height: 216rpx;
				padding: 20rpx;

				.cu-bar-yhj-title {
					color: #333;
					font-size: 32rpx;
					font-weight: 700;
					margin-bottom: 10rpx;
				}

				.cu-bar-yhj-left-time {
					color: #666;
					font-size: 28rpx;
					font-weight: 400;
					margin-top: 10rpx;
				}

				.cu-bar-yhj-right {
					display: flex;
					align-items: center;
					margin-left: 10rpx;

					.cu-bar-yhj-rightBtn {
						width: 142rpx;
						height: 72rpx;
						border-radius: 100px;
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 28rpx;
					}
				}

				.cu-bar-yhj-left-rule {
					color: #999;
					font-size: 24rpx;
					display: inline-block;
					padding: 14rpx 0rpx;
				}

				.rule-con-ul {
					overflow: hidden;
				}

				.activeWy {
					transform: translateY(0%) !important;
					opacity: 1 !important;
					height: auto !important;
					transition: all 0.1s ease-out;
				}

				.rule-con {
					width: 100%;
					color: #999;
					font-size: 24rpx;
					letter-spacing: 0.24px;
					transform: translateY(-120%);
					transition: all .5s;
					height: 0;
					opacity: 0;
					// transform: scale(0);
					// transition: all .5s;
				}
			}
		}

		.title_tips {
			color: #999;
			font-size: 24rpx;
			font-weight: 400;
		}

		.shopyh {
			display: flex;
			padding: 0rpx 30rpx 0rpx 30rpx;
			justify-content: flex-start;
			color: #333;
			font-family: "Microsoft YaHei UI";
			font-size: 32rpx;
			font-weight: 400;
			margin-top: 10rpx;
		}
	}
</style>